package com.toshiba.splashjetinkbd;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.denzcoskun.imageslider.ImageSlider;
import com.denzcoskun.imageslider.constants.ScaleTypes;
import com.denzcoskun.imageslider.models.SlideModel;
import com.toshiba.splashjetinkbd.api.ApiClient;
import com.toshiba.splashjetinkbd.api.ApiInterface;
import com.toshiba.splashjetinkbd.api.Product;
import com.toshiba.splashjetinkbd.db.AppDatabase;
import com.toshiba.splashjetinkbd.model.CartItem;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

// FIXED: Class name now matches file name
public class ProductDetailFragment extends Fragment {

    private static final String TAG = "ProductDetailFragment";
    private static final String ARG_PRODUCT_ID = "PRODUCT_ID";

    // UI Components
    private ImageSlider imageSlider;
    private TextView tvDetailProductName, tvDetailProductPrice, tvDetailProductRegularPrice,
            tvDetailProductModels, tvDetailProductDescription, tvDetailProductSpecification,
            tvDetailProductBrand, tvDetailProductCategory;
    private TextView titleModels, titleDescription, titleSpecification;
    private ImageButton btnShare;
    private Button btnAddToCart, btnBuyNow, btnWhatsappOrder, btnAddReview;
    private RatingBar rbProductRating;

    private Product currentProduct;

    public ProductDetailFragment() {
        // Required empty public constructor
    }

    public static ProductDetailFragment newInstance(int productId) {
        ProductDetailFragment fragment = new ProductDetailFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PRODUCT_ID, productId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_product_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Toolbar toolbar = view.findViewById(R.id.toolbar);
        if (getActivity() != null) {
            ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
            if (((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
                ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
            }
            toolbar.setNavigationOnClickListener(v -> requireActivity().onBackPressed());
        }

        initializeViews(view);

        if (getArguments() != null) {
            int productId = getArguments().getInt(ARG_PRODUCT_ID, -1);
            if (productId != -1) {
                fetchProductDetails(productId);
            }
        }
    }

    private void initializeViews(View view) {
        imageSlider = view.findViewById(R.id.image_slider_detail);
        tvDetailProductName = view.findViewById(R.id.tvDetailProductName);
        tvDetailProductBrand = view.findViewById(R.id.tvDetailProductBrand);
        tvDetailProductCategory = view.findViewById(R.id.tvDetailProductCategory);
        rbProductRating = view.findViewById(R.id.rbProductRating);
        tvDetailProductPrice = view.findViewById(R.id.tvDetailProductPrice);
        tvDetailProductRegularPrice = view.findViewById(R.id.tvDetailProductRegularPrice);
        tvDetailProductModels = view.findViewById(R.id.tvDetailProductModels);
        tvDetailProductDescription = view.findViewById(R.id.tvDetailProductDescription);
        tvDetailProductSpecification = view.findViewById(R.id.tvDetailProductSpecification);

        btnShare = view.findViewById(R.id.btnShare);
        btnAddToCart = view.findViewById(R.id.btnAddToCart);
        btnBuyNow = view.findViewById(R.id.btnBuyNow);
        btnWhatsappOrder = view.findViewById(R.id.btnWhatsappOrder);
        btnAddReview = view.findViewById(R.id.btnAddReview);

        titleModels = view.findViewById(R.id.titleModels);
        titleDescription = view.findViewById(R.id.titleDescription);
        titleSpecification = view.findViewById(R.id.titleSpecification);
    }

    private void fetchProductDetails(int productId) {
        if (getContext() == null) return;

        ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
        Call<Product> call = api.getProductDetails(productId);

        call.enqueue(new Callback<Product>() {
            @Override
            public void onResponse(@NonNull Call<Product> call, @NonNull Response<Product> response) {
                if (!isAdded()) return;

                if (response.isSuccessful() && response.body() != null) {
                    currentProduct = response.body();
                    populateUi(currentProduct);
                } else {
                    Toast.makeText(getContext(), "Failed to load details", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<Product> call, @NonNull Throwable t) {
                if (isAdded()) {
                    Toast.makeText(getContext(), "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void populateUi(Product product) {
        tvDetailProductName.setText(product.getName());
        tvDetailProductBrand.setText(product.getBrandName());
        tvDetailProductCategory.setText(product.getCategory());
        rbProductRating.setRating(product.getRating());

        tvDetailProductPrice.setText("৳ " + product.getOffer_price());
        tvDetailProductRegularPrice.setText("৳ " + product.getRegular_price());
        tvDetailProductRegularPrice.setPaintFlags(tvDetailProductRegularPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

        setupImageSlider(product.getImage_url(), product.getGallery_images());

        setTextOrHide(titleModels, tvDetailProductModels, product.getModels());
        setTextOrHide(titleDescription, tvDetailProductDescription, product.getDescription());
        setTextOrHide(titleSpecification, tvDetailProductSpecification, product.getSpecification());

        btnShare.setOnClickListener(v -> shareProduct(product));
        btnAddToCart.setOnClickListener(v -> addToCart(false));
        btnBuyNow.setOnClickListener(v -> buyNow());
        btnWhatsappOrder.setOnClickListener(v -> orderOnWhatsApp(product));
        btnAddReview.setOnClickListener(v -> Toast.makeText(getContext(), "Coming Soon", Toast.LENGTH_SHORT).show());
    }

    private void setTextOrHide(TextView titleView, TextView contentView, String text) {
        if (text != null && !text.trim().isEmpty() && !text.equalsIgnoreCase("null")) {
            titleView.setVisibility(View.VISIBLE);
            contentView.setVisibility(View.VISIBLE);
            contentView.setText(text);
        } else {
            titleView.setVisibility(View.GONE);
            contentView.setVisibility(View.GONE);
        }
    }

    private void setupImageSlider(String mainImageUrl, String galleryImages) {
        List<SlideModel> imageList = new ArrayList<>();
        if (mainImageUrl != null && !mainImageUrl.isEmpty()) {
            imageList.add(new SlideModel(mainImageUrl, ScaleTypes.CENTER_INSIDE));
        }
        if (galleryImages != null && !galleryImages.isEmpty()) {
            String[] images = galleryImages.split(",");
            for (String img : images) {
                if (!img.trim().isEmpty()) {
                    imageList.add(new SlideModel(img.trim(), ScaleTypes.CENTER_INSIDE));
                }
            }
        }
        imageSlider.setImageList(imageList);
    }

    // FIXED: Reverted to the stable database logic from ProductDetailActivity
    private void addToCart(boolean navigateToCart) {
        if (currentProduct == null || getContext() == null) return;

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            AppDatabase db = AppDatabase.getDatabase(requireContext());
            CartItem existingItem = db.cartDao().getCartItemById(currentProduct.getId());

            if (existingItem != null) {
                existingItem.setQuantity(existingItem.getQuantity() + 1);
                db.cartDao().update(existingItem);
            } else {
                CartItem newItem = new CartItem();
                newItem.setProductId(currentProduct.getId());
                newItem.setProductName(currentProduct.getName());
                newItem.setProductPrice(currentProduct.getOffer_price());
                newItem.setProductImageUrl(currentProduct.getImage_url());
                newItem.setQuantity(1);
                db.cartDao().insert(newItem);
            }

            if (getActivity() != null) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "Added to Cart!", Toast.LENGTH_SHORT).show();
                    if (navigateToCart) {
                        // You will need to implement the navigation logic for your fragment here
                        // e.g., getParentFragmentManager().beginTransaction().replace(R.id.your_container, new CartFragment()).commit();
                    }
                });
            }
        });
    }

    private void buyNow() {
        addToCart(true);
    }

    private void shareProduct(Product product) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Product: " + product.getName());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, "Check out this product: " + product.getName());
        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }

    private void orderOnWhatsApp(Product product) {
        String phoneNumber = "+8801611482988";
        String message = "Hello, I want to order: " + product.getName() + " (ID: " + product.getId() + ")";
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" + URLEncoder.encode(message, "UTF-8");
            intent.setData(Uri.parse(url));
            startActivity(intent); // FIXED: Corrected the incomplete line
        } catch (Exception e) {
            Toast.makeText(getContext(), "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
        }
    }
}